package com.homer.gps.track;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.homer.gps.track.adapters.RoutesArrayAdapter;
import com.homer.gps.track.helper.AnimatedLinearLayout;
import com.homer.gps.track.helper.TracksExporter;
import com.homer.gps.track.helper.UsefullStaff;
import com.homer.gps.track.persist.Repository;
import com.homer.gps.track.persist.RouteModel;
import com.homer.gps.track.persist.StopModel;
import com.homer.gps.track.service.ITrackService;
import com.homer.gps.track.service.TrackService;
import com.homer.gps.track.service.TrackService.MyBinder;
import com.homer.gps.track.template.DefaultORMSherlockActivity;
import com.lowagie.text.DocumentException;

public class Routes extends DefaultORMSherlockActivity implements OnNavigationListener {
	
	private static final int NEW_ROUTE = 101;
	private static final int EDIT_ROUTE = 102;
	
	private ImageButton startStopButton;
    private ListView routesList;
    private TextView elapsedTime;
	private RoutesArrayAdapter routesListAdapter;
	private Repository repository;
	private AnimatedLinearLayout editToolbarLayout;
	private RouteModel runningRoute = null;
	private StopModel startStop = null;
	private Handler updateHandler = null;
	private Runnable updateRunnable = null;
	
	private ServiceConnection trackServiceConnection;
	private ITrackService trackService;
	public static final String TAG = "com.homer.gps.track";

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.routes);
		repository = super.getRepository(this);
		
//		TracksExporter exporter = new TracksExporter(this);
//		exporter.tryit();
		
		trackServiceConnection = new ServiceConnection() {

			public void onServiceDisconnected(ComponentName name) {
				Log.i(TAG, "Track service disconnected");
				trackService = null;
				startAndBindTrackService();
			}

			public void onServiceConnected(ComponentName name, IBinder service) {
				Log.i(TAG, "Net service connected");
				trackService = ((MyBinder) service).getService();
			}
		};

		startAndBindTrackService();
		
		initActivity();
		editToolbarLayout = (AnimatedLinearLayout) findViewById(R.id.edit_toolbar);
		UsefullStaff.checkGpsSettings(this);
		
		this.routesListAdapter = new RoutesArrayAdapter(this, R.layout.routes_list_item, repository.getRoutes());
		routesList = (ListView) findViewById(R.id.routes_list);
		routesList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg) {
				int itemId = routesListAdapter.getItem(position).getId();
				if (routesListAdapter.getItem(position).isRunning()) {
					Intent i = new Intent(Routes.this, RunningRoute.class);
					i.putExtra("createdRouteId", itemId);
					startActivity(i);
				}else{
					Intent i = new Intent(Routes.this, RouteDetail.class);
					i.putExtra("id", itemId);
					startActivityForResult(i, EDIT_ROUTE);
				}
			} 
		});
		routesList.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				routesListAdapter.setDeleteMode(true);
				editToolbarLayout.show();
				return true;
			}
		});
		this.routesList.setAdapter(this.routesListAdapter);
	}
	
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		switch (itemPosition) {
		case 0:
			break;
		case 1:
			Intent i = new Intent(this, Places.class);
			startActivity(i);
			break;
		default:
			break;
		}
		return false;
	}
	
	private void initActivity() {
		Context context = getSupportActionBar().getThemedContext();
        ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.locations, R.layout.sherlock_spinner_item);
        list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        getSupportActionBar().setListNavigationCallbacks(list, this);
        
        getSupportActionBar().setTitle(R.string.title_routes);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setIcon(R.drawable.route_main);
        getSupportActionBar().setHomeButtonEnabled(false);
		getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        
        searchRunningRoute();
	}
	
	private void toggleStartStopButton(boolean trackingEnabled){
		if (trackingEnabled) {
			startStopButton.setImageResource(android.R.drawable.ic_media_pause);
		}else {
			startStopButton.setImageResource(android.R.drawable.ic_media_play);
		}
	}
	
	private void startAndBindTrackService() {
		// just for sure (if the service was killed or something)
		Intent serviceIntent = new Intent(this, TrackService.class);
		startService(serviceIntent);
		bindService(serviceIntent, trackServiceConnection, 0);
	}
	
	public void onSettingsClicked (View view) {
		Intent i = new Intent(this, Settings.class);
		startActivity(i);
	}
	
	public void onNewRouteClicked (View view) {
		Intent i = new Intent(this, RouteEdit.class);
		startActivityForResult(i, NEW_ROUTE);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case NEW_ROUTE:
			if (resultCode == Activity.RESULT_OK) {
				//startAndBindTrackService();
				updateRoutesList();
				Intent i = new Intent(this, RunningRoute.class);
				i.putExtra("createdRouteId", data.getIntExtra("createdRouteId", -1));
				startActivity(i);
				trackService.toggleTracking(data.getIntExtra("createdRouteId", -1));
			}
			break;
		case EDIT_ROUTE:
			if (resultCode == Activity.RESULT_OK) {		
				if (data.getBooleanExtra("stopTracking", false)) {
					trackService.toggleTracking(runningRoute.getId());
					updateHandler.removeCallbacks(updateRunnable);
					runningRoute.toggleRunning();
					repository.saveOrUpdateRoute(runningRoute);
					toggleStartStopButton(runningRoute.isRunning());
				}
				restartActivity();
			}
			break;
		default:
			super.onActivityResult(requestCode, resultCode, data);
			break;
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (trackServiceConnection != null && trackService != null){
			unbindService(trackServiceConnection);
		}
		trackService = null;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		getSupportActionBar().setSelectedNavigationItem(0);
		updateRoutesList();
		searchRunningRoute();
	}
	
	@Override
	public void onBackPressed() {
		trackService = null;
		if (trackServiceConnection != null){
			unbindService(trackServiceConnection);
		}
		finish();
		super.onBackPressed();
	}
	
	public void onDeleteClicked(final View view) {
		new AlertDialog.Builder(this)
		.setTitle("Delete entry")
		.setMessage("Are you sure you want to delete this entry?")
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) { 
				repository.deleteRoute((RouteModel)view.getTag());
				updateRoutesList();
				dialog.dismiss();
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) { 
				dialog.dismiss();
			}
		})
		.show();
	}
	
	public void updateRoutesList(){
		routesListAdapter.clear();
		for(RouteModel route : repository.getRoutes()){
			routesListAdapter.add(route);
			routesListAdapter.notifyDataSetChanged();
		}
	}
	
	public void onCompleteClicked(View view){
		routesListAdapter.setDeleteMode(false);
		editToolbarLayout.hide();
	}
	
	private void setRunningHeader(boolean set){
		View runningRouteHeader = (View) findViewById(R.id.running_route_header);
		View newRouteHeader = (View) findViewById(R.id.new_route_header);
		if (set) {
			runningRouteHeader.setVisibility(View.VISIBLE);
			newRouteHeader.setVisibility(View.GONE);
			elapsedTime = (TextView) findViewById(R.id.elapsed_time);
			updateHandler = new Handler();
			List<StopModel> stops = null;
			try {
				stops = repository.lookupStopsForRoute(runningRoute, StopModel.STOP_TYPE_START);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			startStop = stops.get(0);
			updateRunnable = new Runnable() {
				@Override
				public void run() {
					elapsedTime.setText(UsefullStaff.getElapsedTime(startStop.getStartDateTime()));
					updateHandler.post(this);
				}
			};
			updateHandler.post(updateRunnable);
			startStopButton = (ImageButton) findViewById(R.id.start_stop_button);
			toggleStartStopButton(runningRoute.isRunning());
	        startStopButton.setOnClickListener(new OnClickListener() {

				public void onClick(View arg0) {
					if (runningRoute != null) {
						Intent i = new Intent(Routes.this, RouteEdit.class);
						i.putExtra("id", runningRoute.getId());
						i.putExtra("stopTracking", true);
						startActivityForResult(i, EDIT_ROUTE);
					}
				}
			});
		}else {
			runningRouteHeader.setVisibility(View.GONE);
			newRouteHeader.setVisibility(View.VISIBLE);
		}
	}
	
	private void searchRunningRoute(){
		runningRoute = null;
		for (RouteModel route : repository.getRoutes()) {
			if (route.isRunning()) {
				runningRoute = route;
				setRunningHeader(true);
			}
		}
	}
	
	public void restartActivity() {

	    Intent intent = getIntent();
	    overridePendingTransition(0, 0);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
	    finish();

	    overridePendingTransition(0, 0);
	    startActivity(intent);
	}
}